import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Typography, 
  Switch, 
  Select, 
  Space, 
  Row, 
  Col, 
  message, 
  Radio,
  Button,
} from 'antd';
import { 
  SettingOutlined, 
  BulbOutlined, 
  BellOutlined, 
  UserOutlined, 
  SecurityScanOutlined,
  BgColorsOutlined,
  SmileOutlined
} from '@ant-design/icons';
import { useTheme } from '../store/ThemeContext';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;

interface UserSettings {
  // 外观设置
  theme: 'light' | 'dark' | 'auto';
  primaryColor: string;
  fontSize: 'small' | 'medium' | 'large';
  // 虚拟人物设置
  virtualCharacterEnabled: boolean;
  compactMode: boolean;
  
  // 通知设置
  desktopNotifications: boolean;
  soundEnabled: boolean;
  notificationTypes: string[];
  
  // 隐私设置
  profileVisibility: 'public' | 'friends' | 'private';
  showOnlineStatus: boolean;
  allowFriendRequests: boolean;
  
  // 学习设置
  autoSaveProgress: boolean;
  studyReminders: boolean;
  focusModeEnabled: boolean;
  
  // 聊天设置
  chatSoundEnabled: boolean;
  showTypingIndicator: boolean;
  messagePreview: boolean;
}

const Settings: React.FC = () => {
  const { themeType, setTheme } = useTheme();
  const [settings, setSettings] = useState<UserSettings>({
    theme: 'light',
    primaryColor: '#1890ff',
    fontSize: 'medium',
    virtualCharacterEnabled: true,
    compactMode: false,
    desktopNotifications: true,
    soundEnabled: true,
    notificationTypes: ['study', 'friend', 'system'],
    profileVisibility: 'friends',
    showOnlineStatus: true,
    allowFriendRequests: true,
    autoSaveProgress: true,
    studyReminders: true,
    focusModeEnabled: true,
    chatSoundEnabled: true,
    showTypingIndicator: true,
    messagePreview: true,
  });
  
  const [loading, setLoading] = useState(false);

  // 加载用户设置
  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      setLoading(true);
      // 这里应该从API加载用户设置
      // const response = await userService.getSettings();
      // setSettings(response.data);
    } catch (error) {
      message.error('加载设置失败');
    } finally {
      setLoading(false);
    }
  };

  // 保存设置
  const saveSettings = async (newSettings: Partial<UserSettings>) => {
    try {
      setLoading(true);
      const updatedSettings = { ...settings, ...newSettings };
      setSettings(updatedSettings);
      
      // 这里应该保存到API
      // await userService.updateSettings(updatedSettings);
      
      message.success('设置已保存');
    } catch (error) {
      message.error('保存设置失败');
    } finally {
      setLoading(false);
    }
  };



  return (
    <div style={{ padding: '24px', maxWidth: '1200px', margin: '0 auto' }}>
      <div style={{ marginBottom: '24px' }}>
        <Title level={2}>
          <SettingOutlined style={{ marginRight: '12px' }} />
          系统设置
        </Title>
        <Paragraph type="secondary">
          个性化你的LinkMate体验，调整界面外观、通知偏好和其他功能设置。
        </Paragraph>
      </div>

      <Row gutter={[24, 24]}>
        {/* 外观设置 */}
        <Col xs={24} lg={12}>
          <Card 
            title={
              <Space>
                <BgColorsOutlined style={{ color: '#1890ff' }} />
                外观设置
              </Space>
            }
            loading={loading}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              {/* 主题切换 */}
              <div>
                <Text strong>主题模式</Text>
                <div style={{ marginTop: '8px' }}>
                  <Radio.Group 
                    value={themeType} 
                    onChange={(e) => setTheme(e.target.value)}
                    buttonStyle="solid"
                  >
                    <Radio.Button value="light">
                      <BulbOutlined /> 浅色
                    </Radio.Button>
                    <Radio.Button value="dark">
                      <BulbOutlined /> 深色
                    </Radio.Button>
                  </Radio.Group>
                </div>
              </div>

              {/* 主色调 */}
              <div>
                <Text strong>主色调</Text>
                <div style={{ marginTop: '8px' }}>
                  <Space wrap>
                    {['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2'].map(color => (
                      <div
                        key={color}
                        style={{
                          width: '32px',
                          height: '32px',
                          borderRadius: '6px',
                          backgroundColor: color,
                          cursor: 'pointer',
                          border: settings.primaryColor === color ? '3px solid #fff' : '1px solid #d9d9d9',
                          boxShadow: settings.primaryColor === color ? '0 0 0 2px #1890ff' : 'none',
                        }}
                        onClick={() => saveSettings({ primaryColor: color })}
                      />
                    ))}
                  </Space>
                </div>
              </div>

              {/* 字体大小 */}
              <div>
                <Text strong>字体大小</Text>
                <div style={{ marginTop: '8px' }}>
                  <Select 
                    value={settings.fontSize} 
                    onChange={(value) => saveSettings({ fontSize: value })}
                    style={{ width: '100%' }}
                  >
                    <Option value="small">小</Option>
                    <Option value="medium">中</Option>
                    <Option value="large">大</Option>
                  </Select>
                </div>
              </div>

              {/* 紧凑模式 */}
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>紧凑模式</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        减少界面元素间距，显示更多内容
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.compactMode}
                    onChange={(checked) => saveSettings({ compactMode: checked })}
                  />
                </div>
              </div>

              {/* 虚拟人物 */}
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>虚拟人物</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        在界面上显示可拖动的虚拟角色，增加趣味性
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.virtualCharacterEnabled}
                    onChange={(checked) => {
                      saveSettings({ virtualCharacterEnabled: checked });
                      // 同步更新localStorage
                      localStorage.setItem('virtual-character-enabled', JSON.stringify(checked));
                      // 触发自定义事件通知DraggableIcon组件
                      window.dispatchEvent(new CustomEvent('virtual-character-changed'));
                    }}
                  />
                </div>
                <div style={{ marginTop: '12px' }}>
                  <Button 
                    type="dashed" 
                    icon={<SmileOutlined />}
                    onClick={() => {
                      // 临时启用虚拟人物进行演示
                      const originalValue = settings.virtualCharacterEnabled;
                      saveSettings({ virtualCharacterEnabled: true });
                      localStorage.setItem('virtual-character-enabled', JSON.stringify(true));
                      // 触发自定义事件通知DraggableIcon组件
                      window.dispatchEvent(new CustomEvent('virtual-character-changed'));
                      
                      // 显示提示信息
                      message.success('虚拟人物已启用，您可以在页面上看到可拖动的图标！');
                      
                      // 10秒后恢复原设置（如果原本是关闭的）
                      if (!originalValue) {
                        setTimeout(() => {
                          saveSettings({ virtualCharacterEnabled: false });
                          localStorage.setItem('virtual-character-enabled', JSON.stringify(false));
                          // 触发自定义事件通知DraggableIcon组件
                          window.dispatchEvent(new CustomEvent('virtual-character-changed'));
                          message.info('演示结束，虚拟人物已关闭。如需永久启用，请打开上方开关。');
                        }, 10000); // 10秒后自动关闭
                      }
                    }}
                    style={{ width: '100%' }}
                  >
                    预览虚拟人物演示
                  </Button>
                  <Button 
                    type="primary" 
                    icon={<SmileOutlined />}
                    onClick={() => {
                      // 强制启用虚拟人物
                      console.log('强制启用虚拟人物');
                      saveSettings({ virtualCharacterEnabled: true });
                      localStorage.setItem('virtual-character-enabled', 'true');
                      window.dispatchEvent(new CustomEvent('virtual-character-changed'));
                      message.success('虚拟人物已强制启用！');
                    }}
                    style={{ width: '100%', marginTop: '8px' }}
                  >
                    强制启用虚拟人物
                  </Button>
                </div>
              </div>
            </Space>
          </Card>
        </Col>

        {/* 通知设置 */}
        <Col xs={24} lg={12}>
          <Card 
            title={
              <Space>
                <BellOutlined style={{ color: '#52c41a' }} />
                通知设置
              </Space>
            }
            loading={loading}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>桌面通知</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        在浏览器中显示系统通知
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.desktopNotifications}
                    onChange={(checked) => saveSettings({ desktopNotifications: checked })}
                  />
                </div>
              </div>

              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>声音提醒</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        播放提示音效
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.soundEnabled}
                    onChange={(checked) => saveSettings({ soundEnabled: checked })}
                  />
                </div>
              </div>

              <div>
                <Text strong>通知类型</Text>
                <div style={{ marginTop: '8px' }}>
                  <Select 
                    mode="multiple"
                    value={settings.notificationTypes}
                    onChange={(value) => saveSettings({ notificationTypes: value })}
                    style={{ width: '100%' }}
                    placeholder="选择要接收的通知类型"
                  >
                    <Option value="study">学习提醒</Option>
                    <Option value="friend">好友动态</Option>
                    <Option value="system">系统通知</Option>
                    <Option value="chat">聊天消息</Option>
                  </Select>
                </div>
              </div>
            </Space>
          </Card>
        </Col>

        {/* 隐私设置 */}
        <Col xs={24} lg={12}>
          <Card 
            title={
              <Space>
                <SecurityScanOutlined style={{ color: '#faad14' }} />
                隐私设置
              </Space>
            }
            loading={loading}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <div>
                <Text strong>个人资料可见性</Text>
                <div style={{ marginTop: '8px' }}>
                  <Select 
                    value={settings.profileVisibility}
                    onChange={(value) => saveSettings({ profileVisibility: value })}
                    style={{ width: '100%' }}
                  >
                    <Option value="public">公开</Option>
                    <Option value="friends">仅好友</Option>
                    <Option value="private">私密</Option>
                  </Select>
                </div>
              </div>

              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>显示在线状态</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        让好友看到你的在线状态
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.showOnlineStatus}
                    onChange={(checked) => saveSettings({ showOnlineStatus: checked })}
                  />
                </div>
              </div>

              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>允许好友申请</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        允许其他用户发送好友申请
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.allowFriendRequests}
                    onChange={(checked) => saveSettings({ allowFriendRequests: checked })}
                  />
                </div>
              </div>
            </Space>
          </Card>
        </Col>

        {/* 学习设置 */}
        <Col xs={24} lg={12}>
          <Card 
            title={
              <Space>
                <UserOutlined style={{ color: '#722ed1' }} />
                学习设置
              </Space>
            }
            loading={loading}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>自动保存进度</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        自动保存学习进度和笔记
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.autoSaveProgress}
                    onChange={(checked) => saveSettings({ autoSaveProgress: checked })}
                  />
                </div>
              </div>

              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>学习提醒</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        定期提醒你进行学习
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.studyReminders}
                    onChange={(checked) => saveSettings({ studyReminders: checked })}
                  />
                </div>
              </div>

              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>专注模式</Text>
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        启用专注模式功能
                      </Text>
                    </div>
                  </div>
                  <Switch 
                    checked={settings.focusModeEnabled}
                    onChange={(checked) => saveSettings({ focusModeEnabled: checked })}
                  />
                </div>
              </div>
            </Space>
          </Card>
        </Col>

      </Row>

    </div>
  );
};

export default Settings;